package com.wo.android.pockybill.ui;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import android.R;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
import android.os.Vibrator;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.wo.android.pockybill.BillDuteActivity;
import com.wo.android.pockybill.BillReceiver;
import com.wo.android.pockybill.MainActivity;
import com.wow.wa.bean.DateBean;
import com.wow.wa.bill.serivce.BillService;
import com.wow.wa.bill.serivce.BillServiceImpl;
import com.wow.wa.bill.serivce.CollectDateCompent;
import com.wow.wa.bill.serivce.CollectDateCompentImpl;
import com.wow.wa.bill.serivce.vo.ShareBean;
import com.wow.wa.bill.util.Args;
import com.wow.wa.bill.vo.Bill;
import com.wow.wa.bill.vo.Card;
import com.wow.wa.util.CommonUtils;
import com.wow.wa.util.DateUtils;

public class NotifyComponetImpl implements NotifyComponet {

	private static final String TAG = "NotifyComponetImpl";
	private static final String EVERYDAY_DO = "EVERY_DAY_DO";
	private Context ct;
	private BillService billservice;
	private static Integer BEFORE＿DAY = 3;// 繳費截止日前三天會通知

	private static String CATEGORY_CODE = "tw.com.bill.aler";

	public NotifyComponetImpl(Context ct) {
		billservice = new BillServiceImpl(ct);
		this.ct = ct;
	}

	public Context getCt() {
		return ct;
	}

	// @Override
	public void notifyBill(List<Bill> bills) {
		NotificationManager manger = (NotificationManager) this.getCt()
				.getSystemService(Context.NOTIFICATION_SERVICE);

		Notification msg = new Notification(R.drawable.btn_radio, // 訊息圖示
																	// (會自動縮放)
				"這個是足球 !!", // 要顯示的訊息
				System.currentTimeMillis() // 傳送的時間
		);
		PendingIntent intent = PendingIntent.getActivity(this.getCt(), 0,
				new Intent(this.getCt(), MainActivity.class),
				PendingIntent.FLAG_UPDATE_CURRENT);
		msg.setLatestEventInfo(this.getCt(), "請注意 !!", "這是一顆足球....", intent);
		manger.notify(0, msg);

	}

	// @Override
	public void notifyAllBill() {
		try {
			List<Bill> bills = this.billservice.getBill(this.getCt());
			AlarmManager am = (AlarmManager) this.getCt().getSystemService(
					Context.ALARM_SERVICE);

			for (Bill bill : bills) {
				if (StringUtils.equals(bill.getIsPayed(), Args.Common.STRING_Y)) {
					continue;
				}
				if (StringUtils.isBlank(bill.getDueDate())) {
					continue;
				}

				Intent intent = new Intent(this.getCt(), BillReceiver.class);
				intent.setAction("notify_bill");
				intent.addCategory("" + bill.get_id());

				PendingIntent pi = PendingIntent.getBroadcast(this.getCt(), 1,
						intent, PendingIntent.FLAG_UPDATE_CURRENT);

				// Log.v(TAG, "date.getTime()=" + date.getTime());

				final Card card = this.billservice.getCardByBill(bill);

				// 現金付費類型
				if (StringUtils.equals(card.getType(), Args.Common.STRING_ZERO)) {
					// final DateBean bean = CommonUtils.getDateBean(card
					// .getPayDate());

					// FIXME
					int compareId = DateUtils
							.compareTO(null, new DateBean(), 3);
					switch (compareId) {
					case 0:
					case 1:

						break;
					case 2:
						break;
					}

				}
				// 信用卡類型
				else if (StringUtils.equals(card.getType(),
						Args.Common.STRING_ONE)) {

					// FIXME
					Integer payDate = Integer.parseInt("0");
					Integer nowDate = Integer.parseInt(CommonUtils.getDate());
					// 三天內
					if (payDate + BEFORE＿DAY >= nowDate) {
						am.set(AlarmManager.RTC, SystemClock.elapsedRealtime(),
								pi);
					}
					break;

				}

			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private Calendar getCalendarFromBill(Bill bill) {
		final DateBean bean = CommonUtils.getDateBean(bill.getDueDate());
		Calendar calendar = Calendar.getInstance();
		calendar.set(Calendar.MONTH, bean.getMonth());
		calendar.set(Calendar.YEAR, bean.getYear());
		calendar.set(Calendar.DAY_OF_MONTH, bean.getDay());
		calendar.set(Calendar.HOUR_OF_DAY, 16);
		calendar.set(Calendar.MINUTE, 25);
		calendar.set(Calendar.SECOND, 0);
		return calendar;

	}

	@SuppressWarnings("deprecation")
	// @Override
	public void notifyBill(Bill bill) {
		NotificationManager manger = (NotificationManager) this.getCt()
				.getSystemService(Context.NOTIFICATION_SERVICE);

		@SuppressWarnings("deprecation")
		Notification msg = new Notification(R.drawable.btn_radio, // 訊息圖示
																	// (會自動縮放)
				"時間到了", // 要顯示的訊息
				getCalendarFromBill(bill).getTimeInMillis() // 傳送的時間
		);

		msg.ledARGB = 0xff00ff00;
		msg.ledOnMS = 300;
		msg.ledOffMS = 1000;
		msg.flags |= Notification.FLAG_SHOW_LIGHTS;

		PendingIntent intent = PendingIntent.getActivity(this.getCt(), 0,
				new Intent(this.getCt(), BillDuteActivity.class),
				PendingIntent.FLAG_UPDATE_CURRENT);
		msg.setLatestEventInfo(this.getCt(), "愛注意 !!", "繳費日到了", intent);
		manger.notify(0, msg);

		final Vibrator vibrator = (Vibrator) this.getCt().getSystemService(
				Context.VIBRATOR_SERVICE);
		vibrator.vibrate(300);

	}

	private PendingIntent getPendingIntent(Bill bill, String Action) {

		Intent it = new Intent(this.getCt(), BillReceiver.class);
		it.addCategory(CATEGORY_CODE + "" + bill.get_id());
		it.setAction(Action);
		PendingIntent pi = PendingIntent.getBroadcast(this.ct, REQUESTCODE, it,
				PendingIntent.FLAG_CANCEL_CURRENT);

		return pi;
	}

	private PendingIntent getPendingIntentByEachDay() {
		Intent it = new Intent(this.getCt(), BillReceiver.class);

		it.setAction(NotifyComponet.DAY_TYPE);
		it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent pi = PendingIntent.getBroadcast(this.ct, REQUESTCODE, it,
				PendingIntent.FLAG_UPDATE_CURRENT);
		return pi;
	}

	@Override
	public void eachDayNotiy() {

		AlarmManager am = (AlarmManager) this.getCt().getSystemService(
				Context.ALARM_SERVICE);

		Intent it = new Intent(this.getCt(), BillReceiver.class);

		it.setAction(NotifyComponet.DAY_TYPE);
		it.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		PendingIntent pi = PendingIntent.getBroadcast(this.ct, REQUESTCODE, it,
				PendingIntent.FLAG_NO_CREATE);

	

		final CollectDateCompent compent = new CollectDateCompentImpl(ct);
		final ShareBean bean = compent.readData();

		int alertTime = 9;
		if (StringUtils.isBlank(bean.getAlertTime())) {
			alertTime = 9;
		} else {
			alertTime = Integer.parseInt(bean.getAlertTime());
		}
		
		if (pi != null) {
			Log.v(TAG, "已經註冊了");
		}

		Calendar calender = Calendar.getInstance();
		calender.setTimeInMillis(SystemClock.elapsedRealtime());
		calender.set(Calendar.HOUR, alertTime);
		calender.set(Calendar.MINUTE, 0);
		calender.set(Calendar.SECOND, 0);
		calender.add(Calendar.DAY_OF_MONTH, +1);
		am.setRepeating(AlarmManager.RTC, calender.getTimeInMillis(),
				AlarmManager.INTERVAL_DAY, this.getPendingIntentByEachDay());

		// TODO Auto-generated method stub

	}

	@Override
	public void setAlertAsBill(Bill bill) {
		// TODO Auto-generated method stub

	}

	@Override
	public void notifyNoPayied() {

		final List<Bill> bills = new ArrayList<Bill>();

		try {
			bills.addAll(billservice.getBillWithNoPaid(this.ct));

		} catch (Exception e) {
			Log.v(TAG, e.getMessage());
			e.printStackTrace();
		}

		// 若是沒有尚未繳交清單將不會通知
		if (bills.isEmpty()) {
			return;
		}

		final NotificationManager manger = (NotificationManager) this.getCt()
				.getSystemService(Context.NOTIFICATION_SERVICE);

		@SuppressWarnings("deprecation")
		Notification msg = new Notification(R.drawable.ic_dialog_info, // 訊息圖示
																		// (會自動縮放)
				"時間到了", // 要顯示的訊息
				SystemClock.elapsedRealtime() // 傳送的時間
		);

		NotificationCompat.Builder builder = new NotificationCompat.Builder(
				this.ct);

		new ComponentName(this.ct, BillDuteActivity.class);

		PendingIntent intent = PendingIntent.getActivity(this.getCt(), 0,
				new Intent(this.getCt(), BillDuteActivity.class),

				PendingIntent.FLAG_CANCEL_CURRENT);
		msg.setLatestEventInfo(this.getCt(), "愛注意 !!", "繳費日到了", intent);
		manger.notify(0, msg);
		// final Vibrator vibrator = (Vibrator) this.getCt().getSystemService(
		// Context.VIBRATOR_SERVICE);
		// vibrator.vibrate(300);
	}
}
